package com.slaoren.mvvmexamp.ui

import android.content.res.Configuration
import android.util.Log
import android.widget.Toast
import com.slaoren.mvvmexamp.R
import com.slaoren.mvvmexamp.databinding.ActivityMvvmDemoBinding
import com.slaoren.mvvmexamp.vm.DemoViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

/**
 * 横竖屏切换实现示例之一：
 * Activity不切换横竖屏，实现onConfigurationChanged方法并在其中对Fragment进行切换。
 * 每个Fragment实例化横屏和竖屏两个对象，直接展示对应屏幕方向的Fragment对象。
 * Fragment实现横竖屏两套布局方式，通过mvvm双向绑定的方式同步两个Fragment对象间的的数据。
 */
class MvvmDemo3Activity: BaseActivity<ActivityMvvmDemoBinding, DemoViewModel>(), CoroutineScope by MainScope() {

    override fun getLayoutId(): Int {
        return R.layout.activity_mvvm_demo
    }

    override fun initView() {
        mBinding.vm = mViewModel

        changeFragment("portraitFragment")
    }
    override fun setObserve() {
    }
    override fun loadData() {
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.d("test", "onConfigurationChanged:"+newConfig.orientation)

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){
            Toast.makeText(this, "横屏", Toast.LENGTH_SHORT).show()
            changeFragment("landscapeFragment")
        }else{
            Toast.makeText(this, "竖屏", Toast.LENGTH_SHORT).show()
            changeFragment("portraitFragment")
        }
    }

    private fun changeFragment(tag: String) {
        val fragmentManager = supportFragmentManager
        val fragmentTransaction = fragmentManager.beginTransaction()
        for (fragmentManagerFragment in fragmentManager.fragments) {
            fragmentTransaction.hide(fragmentManagerFragment)
        }
        var fragment = fragmentManager.findFragmentByTag(tag)
        if (fragment != null) {
            fragmentTransaction.show(fragment)
        } else {
            fragment = when(tag){
                "landscapeFragment"->MvvmDemoFragment()
                "portraitFragment"->MvvmDemoFragment()
                else -> null
            }

            if (fragment != null) {
                fragmentTransaction.add(R.id.frameLayout, fragment, tag)
            }
        }
        fragmentTransaction.commitNow()
    }
}